#include "kernel/types.h"
#include "kernel/stat.h"
#include "user/user.h"

int
main(int argc, char *argv[])
{
    if(argc!=1){
        fprintf(2,"usage: pingpong\n");
        exit(1);
    }
    int p[2][2];
    int res=pipe(p[0]);
    if(res==-1){
        printf("failed to create a pipe\n");
        exit(1);
    }
    res=pipe(p[1]);
    if(res==-1){
        printf("failed to create a pipe\n");
        exit(1);
    }
    int pid=fork();
    if(pid==0){
        close(p[0][0]);
        close(p[1][1]);
        int cur_pid=getpid();
        char ch[5];
        read(p[1][0],ch,4);
        ch[4]='\0';
        close(p[1][0]);
        printf("%d: received %s\n",cur_pid,ch);
        write(p[0][1],"pong",4);
        close(p[0][1]);
    }else if(pid>0){
        close(p[1][0]);
        close(p[0][1]);
        int cur_pid=getpid();
        write(p[1][1],"ping",4);
        close(p[1][1]);
        char pr[5];
        read(p[0][0],pr,4);
        pr[4]='\0';
        close(p[0][0]);
        printf("%d: received %s\n",cur_pid,pr);
    } else {
        fprintf(2,"falied to fork\n");
        exit(1);
    }
    exit(0);
}
